﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Threading;

public partial class UserControl_ControlMappingSanPham : System.Web.UI.UserControl
{
    ClassExecute.ClassExecute dt;
    string str = webapp4U.Configuration.CurrentConnectionString;
    string error = "";
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
           
            AddNew();
            LoadNganhHang();
            LoadNhanHieu(ddlNganhHang.SelectedValue.ToString());
            LoadChannel(DropGroup.SelectedValue.ToString()); 
        }
    }
    private void clearDetail()
    {
        if (chPierre.Checked)
        {
            txtMaSo.Text = "";
        }
        else
        {
            txtMaSo.Text = "Mã tự sinh";
        }
        txtFimexSP.Text = "";
       

    }
    void ShowMessageBox(string text)
    {
        MessageBox.Text = text;
        MessageBox.ShowOnPageLoad = true;
    }
    protected void imgBtnAdd_Click(object sender, ImageClickEventArgs e)
    {
        AddNew();
    }
    void AddNew()
    {
        if (ViewState["KhoHangTemp"] != null)
        {
            ViewState["KhoHangTemp"] = null;

        }


        grvProduct.DataSource = null;
        grvProduct.DataBind();

        TabContainer1.ActiveTabIndex = 0;
        clearDetail();
       
       
        btnSave.Text = "Lưu";

       
    }
    void LoadNhanHieu(string CatID)
    {
        dt = new ClassExecute.ClassExecute();
        try
        {
            DataTable db = dt.Get_Data_DataTable(str, ref error, "[k_getInclassFilter]", CommandType.StoredProcedure,
                new SqlParameter("@CatID", CatID));
            dt.BindDropDownList(db, ddlNhanHieu, "MaNhanHieu", "NhanHieu");

        }
        catch (Exception ex)
        {
            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            dt.WriteErrorLog(Server.MapPath(webapp4U.Globals.LogUrl()), ex.Message, method);
        }
    }
    void LoadChannel(string CatID)
    {
         dt = new ClassExecute.ClassExecute();
        try
        {
            DataTable db = dt.Get_Data_DataTable(str, ref error, "[k_getInclassFilter]", CommandType.StoredProcedure,
                new SqlParameter("@CatID", CatID));
            dt.BindDropDownList(db, DropChannel, "MaNhanHieu", "NhanHieu");

        }
        catch (Exception ex)
        {
            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            dt.WriteErrorLog(Server.MapPath(webapp4U.Globals.LogUrl()), ex.Message, method);
        }
    }
    void LoadNganhHang()
    {
        dt = new ClassExecute.ClassExecute();
        try
        {
            DataTable db = dt.Get_Data_DataTable(str, ref error, "[ls_getCategoryList]", CommandType.StoredProcedure);
            dt.BindDropDownList(db, ddlNganhHang, "CommodKey", "Description");
            dt.BindDropDownList(db, DropGroup, "CommodKey", "Description");
        }
        catch (Exception ex)
        {
            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            dt.WriteErrorLog(Server.MapPath(webapp4U.Globals.LogUrl()), ex.Message, method);
        }
    }
    protected void DropGroup_SelectedIndexChanged(object sender, EventArgs e)
    {
        LoadChannel(DropGroup.SelectedValue.ToString());
    }
    //protected void imgBtnDelete_Click(object sender, ImageClickEventArgs e)
    //{
    //    dt = new ClassExecute.ClassExecute();
    //    try
    //    {
    //        int i = dt.ExecuteSQl_int(str, "[k_DeleteMapProduct]", CommandType.StoredProcedure, ref error,
    //            new SqlParameter("@FimexKey", txtMaSo.Text));
    //        if (i == 1)
    //        {
    //            ShowMessageBox("Đã xóa mã trùng sản phẩm thành công và đã cập nhật vào phần phân tuyến sản phẩm cho TDV");
    //            AddNew();
    //            LoadGridDulicated();
    //        }
    //        else
    //        {
    //            ShowMessageBox("Hệ thống đang bảo trì");
    //        }
    //    }
    //    catch (Exception ex)
    //    {

    //        string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
    //        dt.WriteErrorLog(Server.MapPath(webapp4U.Globals.LogUrl()), ex.Message, method);
    //    }    
    //}
    protected void ddlNganhHang_SelectedIndexChanged(object sender, EventArgs e)
    {

        LoadNhanHieu(ddlNganhHang.SelectedValue.ToString());


    }
    void UpdateGridProduct(string itemkey, string sitecode)
    {
        dt = new ClassExecute.ClassExecute();
        DataTable table = new DataTable();
        DataTable db = dt.Get_Data_DataTable(str, ref error, "k_getInfoProductForMap", CommandType.StoredProcedure,
                new SqlParameter("@itemkey", itemkey));
        if (ViewState["KhoHangTemp"] != null)
        {
            table = (DataTable)ViewState["KhoHangTemp"];
            foreach (DataRow dr in table.Rows)
            {
                if (dr[0].ToString() == itemkey)
                {
                    return;
                }
            }

            DataRow row = table.NewRow();
            //Fill All Columns with Data
            row[0] = itemkey;
            row[1] = db.Rows[0]["Description"].ToString();
            row[2] = db.Rows[0]["Group"].ToString();
            row[3] = db.Rows[0]["Channel"].ToString();
            row[4] = sitecode;

            table.Rows.Add(row);
        }
        else
        {


            DataColumn col1 = new DataColumn("MaSP");
            DataColumn col2 = new DataColumn("TenSP");
            DataColumn col3 = new DataColumn("Group");
            DataColumn col4 = new DataColumn("Channel");
            DataColumn col5 = new DataColumn("NPP");


            col1.DataType = System.Type.GetType("System.String");
            col2.DataType = System.Type.GetType("System.String");
            col3.DataType = System.Type.GetType("System.String");
            col4.DataType = System.Type.GetType("System.String");
            col5.DataType = System.Type.GetType("System.String");

            table.Columns.Add(col1);
            table.Columns.Add(col2);
            table.Columns.Add(col3);
            table.Columns.Add(col4);
            table.Columns.Add(col5);



            //Create a Row in the DataTable table
            DataRow row = table.NewRow();
            //Fill All Columns with Data
            row[col1] = itemkey;
            row[col2] = db.Rows[0]["Description"].ToString();
            row[col3] = db.Rows[0]["Group"].ToString();
            row[col4] = db.Rows[0]["Channel"].ToString();
            row[col5] = sitecode;

            table.Rows.Add(row);

            ViewState["KhoHangTemp"] = table;
        }
        grvProduct.DataSource = ViewState["KhoHangTemp"];
        grvProduct.DataBind();

       
    }
    protected void LinkGetDKSH_Click(object sender, EventArgs e)
    {
        grvSP.DataSource = null;
        grvSP.DataBind();
        MessageBoxUserGroup.ShowOnPageLoad = true;
        lblSelectSPFor.Text = "Tìm kiếm những sản phẩm của DKSH";
        ViewState["NPP"] = "FM_00000003";
    }
    protected void LinkGetNMD_Click(object sender, EventArgs e)
    {
        grvSP.DataSource = null;
        grvSP.DataBind();
        MessageBoxUserGroup.ShowOnPageLoad = true;
        lblSelectSPFor.Text = "Tìm kiếm những sản phẩm của Nhật Minh Dương";
        ViewState["NPP"]="FM_00000002";
    }
    protected void grvProduct_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        string keys = grvProduct.DataKeys[e.RowIndex].Value.ToString();

        DataTable table = new DataTable();
        table = (DataTable)ViewState["KhoHangTemp"];

        int i = 0;
        foreach (DataRow dr in table.Rows)
        {
            if (dr[0].ToString() == keys)
            {
                table.Rows[i].Delete();
                table.AcceptChanges();
                ViewState["KhoHangTemp"] = table;
                grvProduct.EditIndex = -1;
                grvProduct.DataSource = ViewState["KhoHangTemp"];
                grvProduct.DataBind();
                return;
            }
            i++;
        }
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        dt = new ClassExecute.ClassExecute();
        try
        {
        
           
                //insert
                if (grvProduct.Rows.Count > 0)
                {
                    string Array = "";
                    DataTable dtLisProduct = new DataTable();
                    dtLisProduct = (DataTable)ViewState["KhoHangTemp"];

                    foreach (DataRow dr in dtLisProduct.Rows)
                    {

                        Array = Array + dr[0].ToString() + ",";

                    }
                    // ShowMessageBox(Array);
                    int i = dt.ExecuteSQl_int(str, "k_mapProduct", CommandType.StoredProcedure, ref error,
                            new SqlParameter("@arrayItemkey", Array.Substring(0, Array.Length - 1)),
                             new SqlParameter("@Desc", txtFimexSP.Text),
                             new SqlParameter("@commodkey",ddlNganhHang.SelectedValue.ToString()),
                             new SqlParameter("@inclasskey",ddlNhanHieu.SelectedValue.ToString()),
                             new SqlParameter("@IsPierre",chPierre.Checked),
                             new SqlParameter("@FimexPierre",txtMaSo.Text));
                    if (i == 1)
                    {
                        ShowMessageBox("Bạn đã map sản phẩm thành công");
                        AddNew();
                       
                    }
                    else
                    {
                        ShowMessageBox("Hệ thống đang bảo trì");
                    }
                }
                else
                {
                    ShowMessageBox("Đề nghị bạn chọn mã sản phẩm muốn Map");
                }
            
        }
        catch (Exception ex)
        {

            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            dt.WriteErrorLog(Server.MapPath(webapp4U.Globals.LogUrl()), ex.Message, method);
        }
    }
    protected void grvSP_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        dt = new ClassExecute.ClassExecute();
        try
        {
            if (e.CommandName == "chon")
            {
                GridViewRow grv = ((Control)e.CommandSource).NamingContainer as GridViewRow;
                Label lblitemkey = (Label)grv.FindControl("lblitemkey");
                if (ViewState["NPP"].ToString() == "FM_00000003")
                {
                    UpdateGridProduct(lblitemkey.Text, "DKSH");
                }
                else if (ViewState["NPP"].ToString() == "FM_00000002")
                {
                    UpdateGridProduct(lblitemkey.Text, "NMD");
                }
            }
        }
        catch (Exception ex)
        {

            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            dt.WriteErrorLog(Server.MapPath(webapp4U.Globals.LogUrl()), ex.Message, method);
        }
    }
    protected void grvSP_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        grvSP.PageIndex = e.NewPageIndex;
        LoadGridSP(DropGroup.SelectedValue.ToString(), DropChannel.SelectedValue.ToString(), ViewState["NPP"].ToString());
    }
    protected void btGetSP_Click(object sender, EventArgs e)
    {
        LoadGridSP(DropGroup.SelectedValue.ToString(), DropChannel.SelectedValue.ToString(), ViewState["NPP"].ToString());
    }
    void LoadGridSP(string Group,string channel,string sitecode)
    {
        dt = new ClassExecute.ClassExecute();
        try
        {
            DataTable db = dt.Get_Data_DataTable(str, ref error, "[k_getInfoProductForSetMap]", CommandType.StoredProcedure,
                new SqlParameter("@commodkey", Group),
                new SqlParameter("@inclasskey", channel),
                new SqlParameter("@sitecode",sitecode));
            if (db.Rows.Count > 0)
            {
                grvSP.DataSource = db;
            }
            else
            {
                grvSP.DataSource = null;
            }
            grvSP.DataBind();
        }
        catch (Exception ex)
        {
            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            dt.WriteErrorLog(Server.MapPath(webapp4U.Globals.LogUrl()), ex.Message, method);
        }
    }
    protected void chPierre_CheckedChanged(object sender, EventArgs e)
    {
        if (chPierre.Checked)
        {
            txtMaSo.Text = "";
        }
        else
        {
            txtMaSo.Text = "Mã tự sinh";
        }
    }
}